package com.ltxtiyu.video.tool;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.vod.upload.impl.UploadVideoImpl;
import com.aliyun.vod.upload.req.UploadStreamRequest;
import com.aliyun.vod.upload.req.UploadVideoRequest;
import com.aliyun.vod.upload.resp.UploadStreamResponse;
import com.aliyun.vod.upload.resp.UploadVideoResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.vod.model.v20170321.*;
import com.ltxtiyu.video.bean.AliVideoInfo;
import org.slf4j.LoggerFactory;
import sun.misc.BASE64Encoder;
import sun.security.jca.GetInstance;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLEncoder;
import java.security.SignatureException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;



@SuppressWarnings("restriction")
public class AliVideoTool {
	
//	private final static Logger LOG = LoggerFactory.getLogger(AliVideoTool.class);
	
	private static org.slf4j.Logger logger =  LoggerFactory.getLogger(AliVideoTool.class);
	
	private final static Logger LOG = Logger.getLogger(AliVideoTool.class.getName());
	
//	private static String access_key_id = SysInfo.CONFIG.get("ACCESSKEYID");         //帐号AK
//	private static String access_key_secret = SysInfo.CONFIG.get("ACCESSKEYSECRET"); //帐号AK

    //STS临时授权方式访问时该参数为必选，使用主账号AK和RAM子账号AK不需要填写
    private static String security_token = "";
    //以下参数不需要修改
//    private final static String VOD_DOMAIN = SysInfo.CONFIG.get("ALIVOD_URL");
    private final static String ISO8601_DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss'Z'";
    private final static String HTTP_METHOD = "GET";
    private final static String HMAC_SHA1_ALGORITHM = "HmacSHA1";
    private final static String UTF_8 = "utf-8";
	
//	private static String alivod_url = SysConfigInfo.CONFIG.get("ACCESSKEYID"); //阿里vod服务接口

//	private static String alivod_play_action = SysInfo.CONFIG.get("ALIVOD_PLAY_ACTION");//阿里vod服务获取播放地址接口
    private static String alivod_list_info_action = "GetVideoInfos";

    private String accessKeyId = "";
    private String accessKeySecret = "";
    private String vodDomain = "";
    private String alivodPlayAction = "";


    public AliVideoTool(String accessKeyId,String accessKeySecret,String vodDomain,String alivodPlayAction){
        this.accessKeyId = accessKeyId;
        this.accessKeySecret = accessKeySecret;
        this.vodDomain = vodDomain;
        this.alivodPlayAction = alivodPlayAction;
    }

    public static AliVideoTool getInstance(String accessKeyId,String accessKeySecret,String vodDomain,String alivodPlayAction){
        return new AliVideoTool(accessKeyId,accessKeySecret,vodDomain,alivodPlayAction);
    }


    private DefaultAcsClient  initClient(){
        DefaultAcsClient aliyunClient;
        aliyunClient = new DefaultAcsClient(
                DefaultProfile.getProfile("cn-shanghai",accessKeyId,accessKeySecret));
        return aliyunClient;
    }

	/**
	 * 上传视频
	 * @param fileName 视频路径
	 * @param videoName 视频标题
	 * @return
	 */
	public String uploadVideo(String accessKeyId,String accessKeySecret, String fileName, String videoName){
		LOG.info("------AilVideoTool:uploadVideo,阿里vod服务上传视频-------");

        UploadVideoRequest request = new UploadVideoRequest(accessKeyId, accessKeySecret, videoName, fileName);
//        request.setCateId(0);                                         //视频分类ID
       // request.setTags("标签1,标签2");                               //视频标签,多个用逗号分隔
       // request.setDescription("视频描述");                           //视频描述
       // request.setCoverURL("http://cover.sample.com/sample.jpg");    //视频自定义封面URL
       // request.setCallback("http://callback.sample.com");            //设置上传完成后的回调URL
        request.setPartSize(1 * 1024 * 1024L);     //可指定分片上传时每个分片的大小，默认为1M字节
        request.setTaskNum(1);                      //可指定分片上传时的并发线程数，默认为1，(注：该配置会占用服务器CPU资源，需根据服务器情况指定）
        request.setIsShowWaterMark(false);           //是否使用水印

        try {
            UploadVideoImpl uploader = new UploadVideoImpl();
            UploadVideoResponse response = uploader.uploadVideo(request);
//            LOG.info(response.getVideoId()); //上传成功后返回视频ID
//            LOG.info(response.getMessage());
            //LOGGER.info(AliTool.getInstance().getAccessURL(response.getVideoId()));
            return response.getVideoId();
        } catch (Exception e) {
        	LOG.info(e.getCause().toString());
        	LOG.info(e.getMessage());
            e.printStackTrace();
            return "";
        }
	}
	

	/**
	 * 获取上传凭证和上传地址
	 * 
	 * @param FileName
	 * @param Title
	 * @return
	 */
	public Map<String, Object> getCreateUploadVideo(String FileName, String Title) {
		logger.info("------------AliVideoTool:getCreateUploadVideo,获取视频上传凭证和上传地址-------------------");
		DefaultAcsClient client = initClient();
		CreateUploadVideoRequest request = new CreateUploadVideoRequest();
		CreateUploadVideoResponse response = null;
		try {
			/*必选，视频源文件名称（必须带后缀, 支持 ".3gp", ".asf", ".avi", ".dat", ".dv",
			".flv", ".f4v", ".gif", ".m2t", ".m3u8", ".m4v", ".mj2",
			".mjpeg", ".mkv", ".mov", ".mp4", ".mpe", ".mpg", ".mpeg",
			".mts", ".ogg", ".qt", ".rm", ".rmvb", ".swf", ".ts", ".vob",
			".wmv", ".webm"".aac", ".ac3", ".acm", ".amr", ".ape", ".caf",
			".flac", ".m4a", ".mp3", ".ra", ".wav", ".wma"）*/
			request.setFileName(FileName);
			// 必选，视频标题
			request.setTitle(Title);
			// 可选，分类ID
//			request.setCateId(0);
			// 可选，视频标签，多个用逗号分隔
//			request.setTags("标签1,标签2");
			// 可选，视频描述
//			request.setDescription("视频描述");
			// 可选，视频源文件字节数
//			request.setFileSize((long) 0);
			response = client.getAcsResponse(request);
		} catch (ServerException e) {
			logger.info("CreateUploadVideoRequest Server Exception:");
			e.printStackTrace();
		} catch (ClientException e) {
			logger.info("CreateUploadVideoRequest Client Exception:");
			e.printStackTrace();
		}
		logger.info("RequestId:" + response.getRequestId());
		logger.info("UploadAuth:" + response.getUploadAuth());
		logger.info("UploadAddress:" + response.getUploadAddress());
		logger.info("videoId:" + response.getVideoId());
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("RequestId", response.getRequestId());
		map.put("UploadAuth", response.getUploadAuth());
		map.put("UploadAddress", response.getUploadAddress());
		map.put("videoId", response.getVideoId());
		return map;
	}

	/**
	 * 重新刷新视频上传地址
	 * @param videoId
	 * @return
	 */
	public Map<String, Object> getRefreshUploadVideo(String videoId) {
		logger.info("------------AliVideoTool:getCreateUploadVideo,刷新视频上传凭证和上传地址,videoId="+videoId+"-------------------");
		DefaultAcsClient client = initClient();
		RefreshUploadVideoRequest request = new RefreshUploadVideoRequest();
		RefreshUploadVideoResponse response = null;
		try {
			request.setVideoId(videoId);
			response = client.getAcsResponse(request);
		} catch (ServerException e) {
			logger.info("RefreshUploadVideoRequest Server Exception:");
			e.printStackTrace();
		} catch (ClientException e) {
			logger.info("RefreshUploadVideoRequest Client Exception:");
			e.printStackTrace();
		}
		logger.info("RequestId:" + response.getRequestId());
		logger.info("UploadAuth:" + response.getUploadAuth());
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("RequestId", response.getRequestId());
		map.put("UploadAuth", response.getUploadAuth());
		return map;
	}
	
	/**
	 * 获取播放信息
	 * @param videoId
	 * @return
	 */
	public Map<String,String> getVideoPlayUrl(String videoId){
		Map<String,String> map = new HashMap<String,String>();
        try {
        	 // 生成私有参数，不同API需要修改
            Map<String, String> privateParams = generatePrivateParamters(videoId,alivodPlayAction);
            //生成公共参数，不需要修改
            Map<String, String> publicParams = generatePublicParamters();
            // 生成OpenAPI地址，不需要修改
            String URL = generateOpenAPIURL(publicParams, privateParams);
        	// 发起请求获取返回参数
        	String result = HttpTool.doGet(URL);
            JSONObject json = JSONObject.parseObject(result);
            // 获取VideoBase数据
            JSONObject videoBase = json.getJSONObject("VideoBase");
            JSONObject playInfoList = json.getJSONObject("PlayInfoList");
            // 获取mp4视频格式
            JSONObject PlayInfo = JSONArray.parseArray(playInfoList.getString("PlayInfo"), JSONObject.class).get(1);
			map.put("PlayURL",PlayInfo.getString("PlayURL"));
			map.put("videoSize", String.valueOf(PlayInfo.get("Size")));
			// 视频持续时间
            /*
            *  1. 主动查询, 单位是秒, float
            *  2. 视频回调, 单位是毫秒
            *  3. 统一单位为毫秒string
            *
            * */
            map.put("Duration",(int)(Float.valueOf(PlayInfo.getString("Duration")) * 1000)+"");
			//获取封面url
			map.put("CoverURL",videoBase.getString("CoverURL"));
			map.put("VideoId", videoBase.getString("VideoId"));
			map.put("Title", videoBase.getString("Title"));
			map.put("Status",videoBase.getString("Status")); // 视频状态  只有 Normal 状态的视频才能播放
		} catch (Exception e) {
			logger.error("-------AliVideoTool:getVideoPlayUrl,获取视频信息失败！-------,错误信息:{}",e);
		}
        return map;
	}

    /**
     * 批量获取播放信息(没有播放地址...)
     * @param videoIds
     * @return
     */
    public Map<String,Object> getVideoInfos(String videoIds){
        Map<String,Object> map = new HashMap<>();
        try {
            //生成私有参数，不同API需要修改
            Map<String, String> privateParams = generatePrivateParamters(videoIds,alivod_list_info_action);
            //生成公共参数，不需要修改
            Map<String, String> publicParams = generatePublicParamters();
            //生成OpenAPI地址，不需要修改
            String URL = generateOpenAPIURL(publicParams, privateParams);
            //发起请求获取返回参数
            String result = HttpTool.doGet(URL);
            com.alibaba.fastjson.JSONObject jsonObject = com.alibaba.fastjson.JSONObject.parseObject(result);
            String requestId = jsonObject.getString("RequestId");
            com.alibaba.fastjson.JSONArray videoArray = jsonObject.getJSONArray("VideoList");
            com.alibaba.fastjson.JSONArray nonExistArray = jsonObject.getJSONArray("NonExistVideoIds");
            List<AliVideoInfo> VideoList = JSON.parseArray(videoArray.toJSONString(), AliVideoInfo.class);
            List<String> NonExistVideoIds = JSON.parseArray(nonExistArray.toJSONString(), String.class);
            map.put("requestId",requestId);
            map.put("VideoList",VideoList);
            map.put("NonExistVideoIds",NonExistVideoIds);
        } catch (Exception e) {
            logger.error("-------AliVideoTool:getVideoInfos,批量获取视频信息失败！-------");
//			e.printStackTrace();
        }
        return map;
    }
	
	 /**
     * 生成视频点播OpenAPI私有参数
     * 不同API需要修改此方法中的参数
     *
     * @return
     */
    private Map<String, String> generatePrivateParamters(String videoId, String action) {
        // 接口私有参数列表, 不同API请替换相应参数
        Map<String, String> privateParams = new HashMap<String, String>();
        // 视频ID
        privateParams.put("VideoId", videoId);
        // API名称
        privateParams.put("Action", action);
        return privateParams;
    }

	
	/**
     * 生成视频点播OpenAPI公共参数
     * 不需要修改
     *
     * @return
     */
    private Map<String, String> generatePublicParamters() {
        Map<String, String> publicParams = new HashMap<String, String>();
        publicParams.put("Format", "JSON");
        publicParams.put("Version", "2017-03-21");
        publicParams.put("AccessKeyId", accessKeyId);
        publicParams.put("SignatureMethod", "HMAC-SHA1");
        publicParams.put("Timestamp", generateTimestamp());
        publicParams.put("SignatureVersion", "1.0");
        publicParams.put("SignatureNonce", generateRandom());
        if (security_token != null && security_token.length() > 0) {
            publicParams.put("SecurityToken", security_token);
        }
        return publicParams;
    }

    /**
     * 流式上传接口
     *
     * @param title
     * @param fileName
     * @param inputStream
     */
    public  static  Map<String ,Object> uploadStream(String access_key_id,String access_key_secret, String title, String fileName, InputStream inputStream) {
        UploadStreamRequest request = new UploadStreamRequest(access_key_id, access_key_secret, title, fileName, inputStream);
         /* 是否使用默认水印(可选)，指定模板组ID时，根据模板组配置确定是否使用默认水印*/
        //request.setShowWaterMark(true);
        /* 设置上传完成后的回调URL(可选)，建议通过点播控制台配置消息监听事件，参见文档 https://help.aliyun.com/document_detail/57029.html */
        //request.setCallback("http://callback.sample.com");
        /* 视频分类ID(可选) */
        request.setCateId(0L);
        /* 视频标签,多个用逗号分隔(可选) */
        //request.setTags("标签1,标签2");
        /* 视频描述(可选) */
        //request.setDescription("视频描述");
        /* 封面图片(可选) */
        //request.setCoverURL("http://cover.sample.com/sample.jpg");
        /* 模板组ID(可选) */
        //request.setTemplateGroupId("8c4792cbc8694e7084fd5330e56a33d");
        /* 存储区域(可选) */
        //request.setStorageLocation("in-201703232118266-5sejdln9o.oss-cn-shanghai.aliyuncs.com");
        UploadVideoImpl uploader = new UploadVideoImpl();
        UploadStreamResponse response = uploader.uploadStream(request);
//        System.out.print("RequestId=" + response.getRequestId() + "\n");  //请求视频点播服务的请求ID
//        if (response.isSuccess()) {
//            System.out.print("VideoId=" + response.getVideoId() + "\n");
//        } else { //如果设置回调URL无效，不影响视频上传，可以返回VideoId同时会返回错误码。其他情况上传失败时，VideoId为空，此时需要根据返回错误码分析具体错误原因
        System.out.print("VideoId=" + response.getVideoId() + "\n");
        System.out.print("ErrorCode=" + response.getCode() + "\n");
        System.out.print("ErrorMessage=" + response.getMessage() + "\n");
//        }
        Map<String ,Object> result = new HashMap<>();
        result.put("videoId",response.getVideoId());
        result.put("ErrorCode",response.getCode());
        result.put("ErrorMessage",response.getMessage());
        return  result;
    }

    /**
     * 生成OpenAPI地址
     * @param privateParams
     * @return
     * @throws Exception
     */
    private String generateOpenAPIURL(Map<String, String> publicParams, Map<String, String> privateParams) {
        return generateURL(vodDomain, HTTP_METHOD, publicParams, privateParams);
    }

    /**
     * @param domain        请求地址
     * @param httpMethod    HTTP请求方式GET，POST等
     * @param publicParams  公共参数
     * @param privateParams 接口的私有参数
     * @return 最后的url
     */
    private String generateURL(String domain, String httpMethod, Map<String, String> publicParams, Map<String, String> privateParams) {
        List<String> allEncodeParams = getAllParams(publicParams, privateParams);
        String cqsString = getCQS(allEncodeParams);
        out("CanonicalizedQueryString = " + cqsString);
        String stringToSign = httpMethod + "&" + percentEncode("/") + "&" + percentEncode(cqsString);
        out("StringtoSign = " + stringToSign);
        String signature = hmacSHA1Signature(accessKeySecret, stringToSign);
        out("Signature = " + signature);
        return domain + "?" + cqsString + "&" + percentEncode("Signature") + "=" + percentEncode(signature);
    }

    private List<String> getAllParams(Map<String, String> publicParams, Map<String, String> privateParams) {
        List<String> encodeParams = new ArrayList<String>();
        if (publicParams != null) {
            for (String key : publicParams.keySet()) {
                String value = publicParams.get(key);
                //将参数和值都urlEncode一下。
                String encodeKey = percentEncode(key);
                String encodeVal = percentEncode(value);
                encodeParams.add(encodeKey + "=" + encodeVal);
            }
        }
        if (privateParams != null) {
            for (String key : privateParams.keySet()) {
                String value = privateParams.get(key);
                //将参数和值都urlEncode一下。
                String encodeKey = percentEncode(key);
                String encodeVal = percentEncode(value);
                encodeParams.add(encodeKey + "=" + encodeVal);
            }
        }
        return encodeParams;
    }

    /**
     * 参数urlEncode
     *
     * @param value
     * @return
     */
    private String percentEncode(String value) {
        try {
            String urlEncodeOrignStr = URLEncoder.encode(value, "UTF-8");
            String plusReplaced = urlEncodeOrignStr.replace("+", "%20");
            String starReplaced = plusReplaced.replace("*", "%2A");
            String waveReplaced = starReplaced.replace("%7E", "~");
            return waveReplaced;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return value;
    }

    /**
     * 获取CQS 的字符串
     *
     * @param allParams
     * @return
     */
    private String getCQS(List<String> allParams) {
        ParamsComparator paramsComparator = new ParamsComparator();
        Collections.sort(allParams, paramsComparator);
        String cqString = "";
        for (int i = 0; i < allParams.size(); i++) {
            cqString += allParams.get(i);
            if (i != allParams.size() - 1) {
                cqString += "&";
            }
        }

        return cqString;
    }

    private class ParamsComparator implements Comparator<String> {
//        @Override
        public int compare(String lhs, String rhs) {
            return lhs.compareTo(rhs);
        }
    }

    private String hmacSHA1Signature(String accessKeySecret, String stringtoSign) {
        try {
            String key = accessKeySecret + "&";
            try {
                SecretKeySpec signKey = new SecretKeySpec(key.getBytes(), HMAC_SHA1_ALGORITHM);
                Mac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM);
                mac.init(signKey);
                byte[] rawHmac = mac.doFinal(stringtoSign.getBytes());
                //按照Base64 编码规则把上面的 HMAC 值编码成字符串，即得到签名值（Signature）
                return new String(new BASE64Encoder().encode(rawHmac));
            } catch (Exception e) {
                throw new SignatureException("Failed to generate HMAC : " + e.getMessage());
            }
        } catch (SignatureException e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 生成随机数
     *
     * @return
     */
    private String generateRandom() {
        String signatureNonce = UUID.randomUUID().toString();
        return signatureNonce;
    }

    /**
     * 生成当前UTC时间戳
     *
     * @return
     */
    public String generateTimestamp() {
        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat df = new SimpleDateFormat(ISO8601_DATE_FORMAT);
        df.setTimeZone(new SimpleTimeZone(0, "GMT"));
        return df.format(date);
    }

    @SuppressWarnings("unused")
	private static String httpGet(String url) throws IOException {
    	/*
         * Read and covert a inputStream to a String.
         * Referred this:
         * http://stackoverflow.com/questions/309424/read-convert-an-inputstream-to-a-string
         */
        out("URL = " +  url);
        @SuppressWarnings("resource")
        Scanner s = new Scanner(new URL(url).openStream(), UTF_8).useDelimiter("\\A");
        try {
            String resposne = s.hasNext() ? s.next() : "true";
            out("Response = " + resposne);
            return resposne;
        } finally {
            s.close();
        }
    }




    private static void out(String newLine) {
        LOG.log(Level.INFO, newLine);
    }


    public String getAccessKeyId() {
        return accessKeyId;
    }

    public void setAccessKeyId(String accessKeyId) {
        this.accessKeyId = accessKeyId;
    }

    public String getAccessKeySecret() {
        return accessKeySecret;
    }

    public void setAccessKeySecret(String accessKeySecret) {
        this.accessKeySecret = accessKeySecret;
    }

    public String getVodDomain() {
        return vodDomain;
    }

    public void setVodDomain(String vodDomain) {
        this.vodDomain = vodDomain;
    }

    public String getAlivodPlayAction() {
        return alivodPlayAction;
    }

    public void setAlivodPlayAction(String alivodPlayAction) {
        this.alivodPlayAction = alivodPlayAction;
    }



    /**
     * 初始化
     * @return
     * @throws ClientException
     */
    public DefaultAcsClient initVodClient() throws ClientException {
        String regionId = "cn-shanghai";  // 点播服务接入区域
        DefaultProfile profile = DefaultProfile.getProfile(regionId, accessKeyId, accessKeySecret);
        DefaultAcsClient client = new DefaultAcsClient(profile);
        return client;
    }


    /**
     * 获取视频上传地址和凭证
     * @return CreateUploadVideoResponse 获取视频上传地址和凭证响应数据
     * @throws Exception
     */
    public Map<String, Object> createUploadVideo(String fileName, String title) {
        logger.info("------------AliVideoTool:createUploadVideo,获取视频上传凭证和上传地址-------------------");
        Map<String, Object> map = new HashMap<>();
        try{
            DefaultAcsClient client = this.initVodClient();
            CreateUploadVideoRequest request = new CreateUploadVideoRequest();
            request.setTitle(title);
            request.setFileName(fileName);
            CreateUploadVideoResponse response = client.getAcsResponse(request);
            logger.info("RequestId:" + response.getRequestId());
            logger.info("UploadAuth:" + response.getUploadAuth());
            logger.info("UploadAddress:" + response.getUploadAddress());
            logger.info("videoId:" + response.getVideoId());
            map.put("RequestId", response.getRequestId());
            map.put("UploadAuth", response.getUploadAuth());
            map.put("UploadAddress", response.getUploadAddress());
            map.put("videoId", response.getVideoId());
        }catch (Exception e){
            logger.error(">>>>>>>>>>>>>>>获取视频上传凭证和上传地址,发生错误:{}",e);
        }
        return map;
    }

    /**
     * 视频合成
     * @param param
     * @return
     */
    public  String  synthesisVideo(Map<String,Object> param){
        try {
            String buildTimeline = (String)param.get("timeline");
            String buildMediaMetadata =(String) param.get("mediaMetadata");
            String buildProduceConfig = (String)param.get("produceConfig");
            DefaultAcsClient client = this.initVodClient();
            ProduceEditingProjectVideoRequest request = new ProduceEditingProjectVideoRequest();
            // Build Editing Project Timeline
            request.setTimeline(buildTimeline);
            // Set Produce Media Metadata
            request.setMediaMetadata(buildMediaMetadata);
            // Set Produce Configuration
            request.setProduceConfig("");
            ProduceEditingProjectVideoResponse response = null;
            response = client.getAcsResponse(request);
            if (response != null){
                String mediaId = response.getMediaId();
                // Produce Media ID
                System.out.println("MediaId:" + response.getMediaId());
                // Request ID
                System.out.println("RequestId:" + response.getRequestId());
                return  mediaId;
            }
        } catch (ServerException e){
            System.out.println("ServerError code:" + e.getErrCode() + ", message:" + e.getErrMsg());
        } catch (ClientException e){
            System.out.println("ClientError code:" + e.getErrCode() + ", message:" + e.getErrMsg());
        } catch (Exception e) {
            System.out.println("ErrorMessage:" + e.getLocalizedMessage());
        }
        return null;
    }

    /**
     * 查询视频当前信息
     * @param aliyunId
     * @return
     */
    public GetVideoInfoResponse.Video queryVideoInfo(String aliyunId){

        try {
            DefaultAcsClient client = this.initVodClient();
            GetVideoInfoRequest request = new GetVideoInfoRequest();
            request.setVideoId(aliyunId);
            GetVideoInfoResponse response = client.getAcsResponse(request);
            if (response != null){
                GetVideoInfoResponse.Video video = response.getVideo();
                return video;
            }else{
                logger.error(">>>>>>>>>>>>>>>查询视频信息失败!");
                return null;
            }

        } catch (Exception e) {
            System.out.print("ErrorMessage = " + e.getLocalizedMessage());
        }
        return null;

    }

    //封装合成的新视频信息
    public static String buildMediaMetadata(String faceImag) {
        JSONObject mediaMetadata = new JSONObject();
        // Produce Media Title
        mediaMetadata.put("Title", "Title");
        // Produce Media Description
        mediaMetadata.put("Description", "Description");
        // Produce Media UserDefined Cover URL
        mediaMetadata.put("CoverURL", faceImag);
        // Produce Media Category ID
        mediaMetadata.put("CateId", null);
        // Produce Media Category Name
        mediaMetadata.put("Tags", "Tag1,Tag2,Test");
        return mediaMetadata.toString();
    }
    //
    public static String buildProduceConfig() {
        JSONObject produceConfig = new JSONObject();
        /*
         The produce process can generate media mezzanine file. You can use the mezzanine file to transcode other media files，just like the transcode process after file upload finished. This field describe the Transocde TemplateGroup ID after produce mezzanine finished.
         1. Not required
         2. Use default transcode template group id when empty
         */
        produceConfig.put("TemplateGroupId", null);
        return produceConfig.toString();
    }
    //合成视频时间线
    public static String buildTimeline(String videoInfos,String videoTail ) {
        String[] split = videoInfos.split(",");
        JSONObject timeline = new JSONObject();
        // Video Track
        JSONArray videoTracks = new JSONArray();
        JSONObject videoTrack = new JSONObject();
        // Video Track Clips
        JSONArray videoTrackClips = new JSONArray();
        for (String aliVideoId : split) {
            JSONObject videoTrackClip = new JSONObject();
            videoTrackClip.put("MediaId", aliVideoId);
            videoTrackClips.add(videoTrackClip);
        }
        //添加片尾
        if (StringUtil.isNotBlank(videoTail)){
            JSONObject videoTrackClip = new JSONObject();
            videoTrackClip.put("MediaId", videoTail);
            videoTrackClips.add(videoTrackClip);
        }
        videoTrack.put("VideoTrackClips", videoTrackClips);
        videoTracks.add(videoTrack);
        timeline.put("VideoTracks", videoTracks);
        return timeline.toString();
    }



}
